/** 
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.tompai.common.file;

/**   
* @Package zz.edu.pseas.weibo.utils 
* @date 2016年6月12日 下午8:36:48 
* @version   
* @since JDK 1.8  
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FilesWithUtils {
	public static final Logger LOG = LoggerFactory.getLogger(FilesWithUtils.class);
	private static String MESSAGE = "";

	/*
	 * 删除文件
	 */
	public static boolean delete(String fileName) {
		boolean result = false;
		File f = new File(fileName);
		if (f.exists()) {
			try {
				result = f.delete();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			result = true;
		}
		return result;
	}

	/*
	 * 读取文件
	 */
	public static String read(String fileName) {
		File f = new File(fileName);
		if (!f.exists()) {
			return "File not found!";
		}
		FileInputStream fs;
		String result = null;
		try {
			fs = new FileInputStream(f);
			byte[] b = new byte[fs.available()];
			fs.read(b);
			fs.close();
			result = new String(b);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	/*
	 * 写文件
	 */
	public static boolean write(String fileName, String fileContent) {
		boolean result = false;
		File f = new File(fileName);
		try {
			FileOutputStream fs = new FileOutputStream(f);
			byte[] b = fileContent.getBytes();
			fs.write(b);
			fs.flush();
			fs.close();
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/*
	 * 追加内容到文件
	 */
	public static boolean append(String fileName, String fileContent) {
		boolean result = false;
		File f = new File(fileName);
		try {
			if (f.exists()) {
				FileInputStream fsIn = new FileInputStream(f);
				byte[] bIn = new byte[fsIn.available()];
				fsIn.read(bIn);
				String oldFileContent = new String(bIn);
				// System.out.println("旧内容:" + oldFileContent);
				fsIn.close();
				if (!oldFileContent.equalsIgnoreCase("")) {
					// fileContent = oldFileContent + System.lineSeparator() +
					// fileContent;
					fileContent = oldFileContent + System.lineSeparator() + fileContent;
					// System.out.println("新内容:" + fileContent);
				}
			}

			FileOutputStream fs = new FileOutputStream(f);
			byte[] b = fileContent.getBytes();
			fs.write(b);
			fs.flush();
			fs.close();
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 复制单个文件
	 * 
	 * @param srcFileName
	 *            待复制的文件名
	 * @param descFileName
	 *            目标文件名
	 * @param overlay
	 *            如果目标文件存在，是否覆盖
	 * @return 如果复制成功返回true，否则返回false
	 */
	public static boolean copyFile(String srcFileName, String destFileName, boolean overlay) {
		File srcFile = new File(srcFileName);

		// 判断源文件是否存在
		if (!srcFile.exists()) {
			MESSAGE = "源文件：" + srcFileName + "不存在！";
			LOG.info(MESSAGE);
			return false;
		} else if (!srcFile.isFile()) {
			MESSAGE = "复制文件失败，源文件：" + srcFileName + "不是一个文件！";
			LOG.info( MESSAGE);
			return false;
		}

		// 判断目标文件是否存在
		File destFile = new File(destFileName);
		if (destFile.exists()) {
			// 如果目标文件存在并允许覆盖
			if (overlay) {
				// 删除已经存在的目标文件，无论目标文件是目录还是单个文件
				new File(destFileName).delete();
			}
		} else {
			// 如果目标文件所在目录不存在，则创建目录
			if (!destFile.getParentFile().exists()) {
				// 目标文件所在目录不存在
				if (!destFile.getParentFile().mkdirs()) {
					// 复制文件失败：创建目标文件所在目录失败
					return false;
				}
			}
		}

		// 复制文件
		int byteread = 0; // 读取的字节数
		InputStream in = null;
		OutputStream out = null;

		try {
			in = new FileInputStream(srcFile);
			out = new FileOutputStream(destFile);
			byte[] buffer = new byte[1024];

			while ((byteread = in.read(buffer)) != -1) {
				out.write(buffer, 0, byteread);
			}
			return true;
		} catch (FileNotFoundException e) {
			return false;
		} catch (IOException e) {
			return false;
		} finally {
			try {
				if (out != null)
					out.close();
				if (in != null)
					in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 复制整个目录的内容
	 * 
	 * @param srcDirName
	 *            待复制目录的目录名
	 * @param destDirName
	 *            目标目录名
	 * @param overlay
	 *            如果目标目录存在，是否覆盖
	 * @return 如果复制成功返回true，否则返回false
	 */
	public static boolean copyDirectory(String srcDirName, String destDirName, boolean overlay) {
		// 判断源目录是否存在
		File srcDir = new File(srcDirName);
		if (!srcDir.exists()) {
			MESSAGE = "复制目录失败：源目录" + srcDirName + "不存在！";
			LOG.info( MESSAGE);
			return false;
		} else if (!srcDir.isDirectory()) {
			MESSAGE = "复制目录失败：" + srcDirName + "不是目录！";
			LOG.info( MESSAGE);
			return false;
		}

		// 如果目标目录名不是以文件分隔符结尾，则加上文件分隔符
		if (!destDirName.endsWith(File.separator)) {
			destDirName = destDirName + File.separator;
		}
		File destDir = new File(destDirName);
		// 如果目标文件夹存在
		if (destDir.exists()) {
			// 如果允许覆盖则删除已存在的目标目录
			if (overlay) {
				new File(destDirName).delete();
			} else {
				MESSAGE = "复制目录失败：目的目录" + destDirName + "已存在！";
				LOG.info( MESSAGE);
				return false;
			}
		} else {
			// 创建目的目录
			LOG.error("目的目录不存在，准备创建...");
			if (!destDir.mkdirs()) {
				LOG.error("复制目录失败：创建目的目录失败！");
				return false;
			}
		}

		boolean flag = true;
		File[] files = srcDir.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 复制文件
			if (files[i].isFile()) {
				flag = CopyFileUtil.copyFile(files[i].getAbsolutePath(), destDirName + files[i].getName(), overlay);
				if (!flag)
					break;
			} else if (files[i].isDirectory()) {
				flag = CopyFileUtil.copyDirectory(files[i].getAbsolutePath(), destDirName + files[i].getName(),
						overlay);
				if (!flag)
					break;
			}
		}
		if (!flag) {
			MESSAGE = "复制目录" + srcDirName + "至" + destDirName + "失败！";
			LOG.info( MESSAGE);
			return false;
		} else {
			return true;
		}
	}
}
